import logging
from fastapi import APIRouter, Query,Request
from app.controllers.system.menu import menu_controller
from app.core.redis_base import redis_get,redis_set
from app.schemas.base import Fail, Success, SuccessExtra
from app.schemas.menus import *

logger = logging.getLogger(__name__)
menus_router = APIRouter()

@menus_router.get("/list", summary="查看菜单列表")
async def list_menu(
        request: Request,
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    res_menu = await redis_get("system:all_menu", request.state.redis)
    if res_menu is None:
        parent_menus = await menu_controller.model.filter(parent_id=0).order_by("order")
        res_menu = [await menu_controller.get_menu_with_children(menu.id) for menu in parent_menus]
        await redis_set("system:all_menu",res_menu,request.state.redis)
    return SuccessExtra(data=res_menu, total=len(res_menu), page=page, page_size=page_size)


@menus_router.get("/get", summary="查看菜单")
async def get_menu(
        menu_id: int = Query(..., description="菜单id"),
):
    result = await menu_controller.get(id=menu_id)
    return Success(data=result)


@menus_router.post("/create", summary="创建菜单")
async def create_menu(
        request: Request,
        menu_in: MenuCreate,
):
    await menu_controller.create(obj_in=menu_in)
    await request.state.redis.delete("system:all_menu")
    return Success(msg="Created Success")


@menus_router.post("/update", summary="更新菜单")
async def update_menu(
        request: Request,
        menu_in: MenuUpdate,
):
    await menu_controller.update(id=menu_in.id, obj_in=menu_in)
    await request.state.redis.delete("system:all_menu")
    return Success(msg="Updated Success")


@menus_router.delete("/delete", summary="删除菜单")
async def delete_menu(
        request: Request,
        id: int = Query(..., description="菜单id"),
):
    child_menu_count = await menu_controller.model.filter(parent_id=id).count()
    if child_menu_count > 0:
        return Fail(msg="无法删除,请先删除子菜单")
    await menu_controller.remove(id=id)
    await request.state.redis.delete("system:all_menu")
    return Success(msg="Deleted Success")
